package org.datascooter.bundle.attribute;

import java.lang.reflect.Field;

import org.datascooter.exception.DataScooterException;

/**
 * This class purposed for mapping a persisted child objects. This objects, contained in parent in runtime and will be persisted with parent and tables may be linked with references
 * 
 * @author nemo
 * 
 */
public class PersistChildFieldAttribute extends PersistChildAttribute {

	private Field field;

	public PersistChildFieldAttribute(String name, String entity, String mapKeyAttribute, PersistencePolicy policy, boolean embedded, boolean fetchLazy, String joinAttribute, Boolean joinFromChild) {
		super(name, entity, mapKeyAttribute, policy, embedded, fetchLazy, joinAttribute, joinFromChild);
	}

	@Override
	public void explore(Class<?> clazz) {
		try {
			super.explore(clazz);
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		}
		if (clazz != null) {
			Class<?> clazz1 = clazz;
			while (field == null) {
				try {
					field = clazz1.getDeclaredField(name);
				} catch (Exception e) {
					clazz1 = clazz1.getSuperclass();
					if (clazz1 == null) {
						throw new DataScooterException("***No field found  " + e.getMessage());
					}
				}
			}
			returnType = field.getType();
			field.setAccessible(true);
			setGetClass(returnType);
			setSetClass(returnType);
		}
	}

	@Override
	public <T> Object getValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
		return field.get(obj);
	}

	@Override
	public void setValue(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException {
		field.set(obj, value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AbstractAttribute> T copy() {
		return (T) new PersistChildFieldAttribute(name, entity, mapKeyAttribute, policy, embedded, fetchLazy, joinAttribute, joinFromChild);
	}
}
